<template>
  <div class="user-list-container">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="filter-container">
        <el-input
            v-model="listQuery.username"
            placeholder="搜索用户名"
            style="width: 300px"
            clearable
            @keyup.enter="handleFilter"
        />
        <el-button type="primary" @click="handleFilter">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button type="success" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加管理员
        </el-button>
      </div>

      <!-- 添加管理员弹窗 -->
      <el-dialog
          v-model="dialogVisible"
          title="添加修改管理员"
          width="500px"
          :close-on-click-modal="false"
      >
        <el-form
            ref="userFormRef"
            :model="userForm"
            :rules="userRules"
            label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
                v-model="userForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
            />
          </el-form-item>
          <el-form-item label="昵称" prop="username">
            <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-radio-group v-model="userForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddUser">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 用户表格 -->
      <el-table
          :data="tableData"
          border
          fit
          highlight-current-row
          style="width: 100%"
          v-loading="listLoading"
      >
        <el-table-column prop="id" label="ID" width="180" align="center" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="nickname" label="昵称" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最近登录时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.lastLogin).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="200">
          <template #default="{ row }">
            {{ new Date(row.createdAt).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button
                size="small"
                :type="row.status === 1 ? 'warning' : 'success'"
                @click="handleStatusChange(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="listQuery.page"
          v-model:page-size="listQuery.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getList"
          @current-change="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search ,Plus} from '@element-plus/icons-vue'
import axios from '@/utils/request' // 假设已经封装了axios实例
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([])
const total = ref(0)
const listLoading = ref(false)

// 查询参数
const listQuery = reactive({
  page: 1,
  pageSize: 10,
  username: ''
})

// 添加管理员相关状态
const dialogVisible = ref(false)
const userFormRef = ref(null)
const userForm = reactive({
  username: '',
  nickname: '',
  password: '',
  status: 1, // 默认启用
})

// 表单验证规则
const userRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ]
})

// 显示添加用户弹窗
const showAddDialog = () => {
  // 重置表单
  Object.assign(userForm, {
    id:0,
    username: '',
    nickname: '',
    password: '',
    status: 1
  })

  // 如果有表单实例，清除验证
  if (userFormRef.value) {
    userFormRef.value.clearValidate()
  }

  dialogVisible.value = true
}

const handleEdit = (row)=>{
  console.log(row)
  // 重置表单
  Object.assign(userForm, {
    id:row.id,
    username: row.username,
    nickname: row.nickname,
    password: row.password,
    status: row.status
  })

  // 如果有表单实例，清除验证
  if (userFormRef.value) {
    userFormRef.value.clearValidate()
  }

  dialogVisible.value = true
}

// 添加用户提交
const handleAddUser = () => {
  userFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      // 调用添加用户API
      const response = await axios.post('/admin/admin/save', userForm)
      console.log(response)
      ElMessage.success('管理员添加成功')
      dialogVisible.value = false
      getList() // 刷新用户列表
    } catch (error) {
      ElMessage.error('添加管理员失败: ' + (error.response?.data?.message || error.message))
    }
  })
}

// 获取用户列表
const getList = async () => {
  listLoading.value = true
  try {
    const response = await axios.get('/admin/admin/list', {
      params: listQuery
    })

    tableData.value = response.data.list || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    listLoading.value = false
  }
}

// 搜索
const handleFilter = () => {
  listQuery.page = 1
  getList()
}


// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确认删除用户 ${row.username} 吗?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      // 调用接口修改状态
      await axios.post('/admin/admin/delete', {
        id: row.id,
      })

      ElMessage.success('操作成功')
      getList() // 刷新列表
    } catch (error) {
      ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 修改用户状态
const handleStatusChange = (row) => {
  ElMessageBox.confirm(
      `确认${row.status === 1 ? '禁用' : '启用'}用户 ${row.username} 吗?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      // 调用接口修改状态
      await axios.post('/admin/admin/changeStatus', {
        id: row.id,
        status: row.status === 1 ? 0 : 1
      })

      ElMessage.success('操作成功')
      getList() // 刷新列表
    } catch (error) {
      ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 初始化获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.box-card {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>